package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"go_demo_1/common"
	"go_demo_1/conf"
	"log"
	"net/http"
	"os"
)

func main() {
	//数据库手动连接
	issucc := common.GetInstance().InitDataPool()
	if !issucc {
		log.Println("init database pool failure...")
		os.Exit(1)
	}
	// init logger
	if err := common.InitLogger(); err != nil {
		fmt.Printf("init logger failed, err:%v\n", err)
		return
	}

	// init redis
	common.InitRedisClient()

	gin.SetMode(conf.Conf.App.Mode) //加载配置文件
	if gin.Mode() == gin.ReleaseMode {
		// Release模式
		gin.DisableConsoleColor()
		logfile := conf.Conf.App.LogFile
		if logfile == "" {
			log.Fatalln("Please set the log file path!")
		}

		file, err := os.OpenFile(logfile, os.O_RDWR|os.O_CREATE|os.O_APPEND, os.ModePerm)
		if err != nil {
			file, err = os.Create(logfile)
			if file == nil {
				log.Fatalln(err)
			}
		}

		defer func() {
			err := file.Close()
			if err != nil {
				log.Fatalln(err)
			}
		}()

		gin.DefaultWriter = file
		log.SetOutput(file)
	} else {
		// Debug模式
		go func() {
			err := http.ListenAndServe(":8080", nil)
			if err != nil {
				log.Fatalln(err)
			}
		}()

	}

	var err error
	//加载路由
	r := initRouter()
	err = r.Run(":" + conf.Conf.Http.Port)
	if err != nil {
		log.Fatalln("Something terrible happened:", err)
	}

	defer common.Db.Close()
}
